# Functions
So far we have seen and used functions from an Arduino library. A function is a block of code that runs only when we make a call to that function. We can pass data (parameters) to the function. Using functions is a good practice to be able to effectively reuse code.
# Declaring a Function
We will start with a simple function:
void functionName()
{
//code inside the function
}
The above code declares a function named functionName
. A function declaration starts with a type. This is called the return type of the function. A function can return a variable, we will learn more about the return type in the next example. However, specifying the return type to be void
means this function will not return anything. Whenever we call this function, it will only run the code inside of it.
After the return type, we specify the name of the function. We need to give the function a name so that we can use it afterwards.
To specify that this is a function, we need to use ( )
after the function name and then start the scope of the function {
.
Inside this scope we will define what we want this function to do each time we call it.
# Calling a Function
We use the name of the function followed by ()
to call the function and execute the code block inside of it.
Homework
The code below declares a function sayHello
that prints Hello to the Serial. Inside the loop function we are making a call to our function and then waiting for 1 second.
However, the code will not compile successfully. Fix the error.